<template>
  <div class="debug-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>入库单明细数据调试工具</span>
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </template>

      <!-- 入库单列表 -->
      <div class="section">
        <h3>入库单列表</h3>
        <el-table :data="inboundOrders" border style="width: 100%" max-height="300">
          <el-table-column prop="entryOrderNumber" label="入库单号" width="180" />
          <el-table-column prop="entryType" label="入库类型" width="120" />
          <el-table-column prop="createdBy" label="创建人" width="120" />
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="checkDetails(row.entryOrderNumber)">
                检查明细
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 明细检查结果 -->
      <div class="section" v-if="selectedOrderNumber">
        <h3>入库单明细检查结果 - {{ selectedOrderNumber }}</h3>
        
        <!-- API调用信息 -->
        <el-alert 
          :title="`API调用: /api/InboundOrder/GetProductDetails/${selectedOrderNumber}`"
          type="info" 
          :closable="false"
          style="margin-bottom: 16px"
        />

        <!-- 原始响应数据 -->
        <div class="raw-data">
          <h4>原始API响应:</h4>
          <pre>{{ JSON.stringify(rawResponse, null, 2) }}</pre>
        </div>

        <!-- 处理后的数据 -->
        <div class="processed-data" v-if="processedDetails.length > 0">
          <h4>处理后的明细数据:</h4>
          <el-table :data="processedDetails" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="productId" label="产品ID" width="100" />
            <el-table-column prop="productName" label="产品名称" width="150" />
            <el-table-column prop="productCode" label="产品编号" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="num" label="数量" width="80" />
            <el-table-column prop="entryOrderNumber" label="入库单号" width="150" />
          </el-table>
        </div>

        <!-- 错误信息 -->
        <div class="error-info" v-if="errorMessage">
          <el-alert :title="errorMessage" type="error" :closable="false" />
        </div>

        <!-- 数据库查询建议 -->
        <div class="suggestions">
          <h4>数据库查询建议:</h4>
          <el-alert 
            title="请在后端数据库中执行以下查询来检查数据是否正确保存:"
            type="warning"
            :closable="false"
          />
          <pre class="sql-query">
-- 检查入库单是否存在
SELECT * FROM InboundOrder WHERE entryOrderNumber = '{{ selectedOrderNumber }}';

-- 检查产品明细是否存在
SELECT * FROM ProductDetail WHERE entryOrderNumber = '{{ selectedOrderNumber }}';

-- 检查所有相关表的数据
SELECT pd.*, io.entryOrderNumber 
FROM ProductDetail pd 
LEFT JOIN InboundOrder io ON pd.entryOrderNumber = io.entryOrderNumber 
WHERE pd.entryOrderNumber = '{{ selectedOrderNumber }}';
          </pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllInboundOrders, getInboundOrderDetails } from '@/api/warehouseReceipt'

const inboundOrders = ref<any[]>([])
const selectedOrderNumber = ref('')
const rawResponse = ref<any>(null)
const processedDetails = ref<any[]>([])
const errorMessage = ref('')

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

const refreshData = async () => {
  try {
    const response = await getAllInboundOrders()
    if (response.code === 200) {
      inboundOrders.value = response.data
      ElMessage.success('数据刷新成功')
    } else {
      ElMessage.error('获取入库单列表失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

const checkDetails = async (entryOrderNumber: string) => {
  selectedOrderNumber.value = entryOrderNumber
  rawResponse.value = null
  processedDetails.value = []
  errorMessage.value = ''

  console.log('开始检查入库单明细:', entryOrderNumber)

  try {
    const response = await getInboundOrderDetails(entryOrderNumber)
    rawResponse.value = response
    
    console.log('API响应:', response)

    if (response.code === 200) {
      if (Array.isArray(response.data) && response.data.length > 0) {
        processedDetails.value = response.data.map((d: any, index: number) => ({
          index: index + 1,
          id: d.id || d.productDetailId || d.detailId || '无ID',
          productId: d.productId || '无产品ID',
          productName: d.productName || '无产品名称',
          productCode: d.productNumber || d.productCode || '无产品编号',
          unit: d.inventoryUnit || d.unit || '无单位',
          num: d.num || d.inventoryQuantity || 0,
          entryOrderNumber: d.entryOrderNumber || '无入库单号',
          rawData: JSON.stringify(d)
        }))
        ElMessage.success(`找到 ${processedDetails.value.length} 条明细数据`)
      } else {
        errorMessage.value = '该入库单没有找到任何产品明细数据'
        ElMessage.warning('没有找到明细数据')
      }
    } else {
      errorMessage.value = `API调用失败: ${response.msg || '未知错误'}`
      ElMessage.error('获取明细数据失败')
    }
  } catch (error: any) {
    console.error('检查明细失败:', error)
    errorMessage.value = `请求失败: ${error.message || '网络错误'}`
    ElMessage.error('检查明细失败')
  }
}

onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.debug-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section {
  margin-bottom: 30px;
}

.section h3 {
  margin-bottom: 16px;
  color: #303133;
}

.section h4 {
  margin: 16px 0 8px 0;
  color: #606266;
}

.raw-data pre,
.sql-query {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.4;
}

.suggestions {
  margin-top: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.error-info {
  margin: 16px 0;
}

.processed-data {
  margin: 16px 0;
}
</style>